function open(entry) {
  chrome.runtime.getBackgroundPage(function(bg) {
    bg.open(entry);
  });
}

function onButtonClick(event) {
  var options = {
    type: 'openFile',
    acceptsMultiple: true,
    acceptsAllTypes: false,
    accepts: [{ extensions: ['cbr'] }],
  };
  chrome.fileSystem.chooseEntry(options, function(entries) {
    for (var i = 0; i < entries.length; i++)
      open(entries[i]);
  });
}

function onBookClick() {
  var filename = this.textContent;
  chrome.syncFileSystem.requestFileSystem(function(fileSystem) {
    fileSystem.root.getFile(filename, { create: false }, function(entry) {
      open(entry);
    });
  });
}

chrome.syncFileSystem.requestFileSystem(function(fileSystem) {
  var reader = fileSystem.root.createReader();
  reader.readEntries(function(entries) {
    for (var i = 0; i < entries.length; i++) {
      var entryName = entries[i].name;
      if (entryName.substr(-4) === '.cbr') {
        var button = document.createElement('button');
        button.textContent = entryName;
        button.addEventListener('click', onBookClick);
        document.body.appendChild(button);
      }
    }
  });
});


function removeContextMenus() {
  chrome.contextMenus.removeAll();
};

window.addEventListener('focus', removeContextMenus);


var button = document.querySelector('#filePicker');
button.addEventListener('click', onButtonClick);

